{
 "cells": [
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "大衍之数五十，其用四十有九。  \n",
    "分而为二以象两，挂一以象三，揲之以四以象四时，归奇于扐以象闺，故再扐而后挂。  \n",
    "乾之策二百一十有六，坤之策百四十有四，凡三百六十，当期之日。  \n",
    "二篇之策，万有一千五百二十，当万物之数也。是故四营而成易，十有八变而成卦。  "
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "实现六爻算法——完成  \n",
    "通过sqllite搭两个关系——完成  \n",
    "查询数据库取卦——完成  \n",
    "变卦取爻逻辑需补充——完成  \n",
    "需补充卦辞及爻辞表——完成  \n",
    "尝试写成API"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 15,
   "metadata": {},
   "outputs": [],
   "source": [
    "import random\n",
    "import sqlite3\n",
    "import pandas as pd"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 16,
   "metadata": {},
   "outputs": [],
   "source": [
    "#(大衍之数五十，其用四十有九)\n",
    "full = 50\n",
    "one = 1\n",
    "use = full-one"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 17,
   "metadata": {},
   "outputs": [],
   "source": [
    "def yao(use):\n",
    "    #分而为二以象两\n",
    "    left = random.randint(0,use)\n",
    "    right= use-left\n",
    "    #挂一以象三\n",
    "    first = 1\n",
    "    left -= 1\n",
    "    #揲之以四以象四时\n",
    "    left_c=left%4\n",
    "    if left_c==0:\n",
    "        first += 4\n",
    "        left -= 4\n",
    "    else:\n",
    "        first += left_c\n",
    "        left -= left_c\n",
    "    right_c=right%4\n",
    "    if right_c==0:\n",
    "        first += 4\n",
    "        right -= 4\n",
    "    else:\n",
    "        first += right_c\n",
    "        right -= right_c  \n",
    "    #归奇于扐以象闺\n",
    "    return left+right"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 18,
   "metadata": {},
   "outputs": [],
   "source": [
    "#故再扐而后挂。——这里成爻\n",
    "def gua(use):\n",
    "    for i in range (3):\n",
    "        use=yao(use)\n",
    "    return use/4\n",
    "#数——这里输出6个数\n",
    "list_n = []\n",
    "for i in range(6):\n",
    "    a= gua(use)\n",
    "    list_n.append(a)\n",
    "#翻转列表——其实可以不翻，但是读挂还是习惯从上往下读\n",
    "list_n.reverse()\n",
    "#本卦——纯图示，意义不大，已经转成数据库直接读了。\n",
    "list_gua = []\n",
    "for i in range(len(list_n)):\n",
    "    if list_n[i] % 2 == 0 :\n",
    "        yao = \"- -\"\n",
    "    else:\n",
    "        yao = \"---\"\n",
    "    list_gua.append(yao)\n",
    "#变——纯图示，意义不大，已经转成数据库直接读了。\n",
    "list_bian = []\n",
    "for i in range(len(list_n)):\n",
    "    if list_n[i] in (6,9) :\n",
    "        bian = \"变\"\n",
    "    else:\n",
    "        bian = \"不变\"\n",
    "    list_bian.append(bian)\n",
    "#之卦\n",
    "list_bian1 = []\n",
    "for i in range(len(list_n)):\n",
    "    if list_n[i] < 8 :\n",
    "        bian = \"---\"\n",
    "    else:\n",
    "        bian = \"- -\"\n",
    "    list_bian1.append(bian)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 19,
   "metadata": {},
   "outputs": [],
   "source": [
    "#df基础形态\n",
    "tb={\"数\": list_n,\n",
    "    \"卦\": list_gua,\n",
    "    \"变\": list_bian,\n",
    "    \"之\": list_bian1}\n",
    "df= pd.DataFrame(tb)\n",
    "df.reset_index(inplace=True)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 20,
   "metadata": {},
   "outputs": [],
   "source": [
    "# 数据库链接\n",
    "con = sqlite3.connect('yi.db')\n",
    "sql = '''SELECT hexagram FROM hexagram WHERE num = \"%s\"'''"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 21,
   "metadata": {},
   "outputs": [],
   "source": [
    "#卦数转sql求卦\n",
    "gua_num = []\n",
    "for i in range(len(list_n)):\n",
    "    g_num =str(round(list_n[i] % 2))\n",
    "    gua_num.append(g_num)\n",
    "gua_str=\"\" \n",
    "gua_str= gua_str.join(gua_num)\n",
    "gua_str\n",
    "df_in= pd.read_sql(sql%gua_str,con)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 22,
   "metadata": {},
   "outputs": [],
   "source": [
    "# 之数转sql求卦\n",
    "zhi_num=[]\n",
    "for i in range(len(list_n)):\n",
    "    if list_n[i] < 8 :\n",
    "        zhi=\"1\"\n",
    "    else:\n",
    "        zhi = \"0\"\n",
    "    zhi_num.append(zhi)\n",
    "zhi_str=\"\"\n",
    "zhi_str=zhi_str.join(zhi_num)\n",
    "df_out= pd.read_sql(sql%zhi_str,con)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 23,
   "metadata": {},
   "outputs": [],
   "source": [
    "#变\n",
    "list_bian = []\n",
    "for i in range(len(list_n)):\n",
    "    if list_n[i] in (6,9) :\n",
    "        bian = \"变\"\n",
    "    else:\n",
    "        bian = \"不变\"\n",
    "    list_bian.append(bian)\n",
    "df_bian = pd.DataFrame(list_bian,columns=[\"变\"])"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 24,
   "metadata": {},
   "outputs": [],
   "source": [
    "sql_y = '''SELECT\n",
    "\ty.records as desc\n",
    "FROM\n",
    "\thexagram g,\n",
    "\tyao y\n",
    "WHERE\n",
    "\tg.id = y.hexagram_id\n",
    "\tAND\n",
    "\ty.yao = \"%s\"\n",
    "\tand\n",
    "\tg.num = \"%s\"'''"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 25,
   "metadata": {},
   "outputs": [],
   "source": [
    "sql_g = '''SELECT\n",
    "\trecords as desc\n",
    "FROM\n",
    "\thexagram \n",
    "WHERE\n",
    "    num = \"%s\"'''"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 26,
   "metadata": {},
   "outputs": [],
   "source": [
    "\n",
    "if len(df[df[\"变\"]==\"变\"])==0:\n",
    "    say = \"无变爻，取本卦卦辞\"\n",
    "    main = pd.read_sql(sql_g%gua_str,con)[\"desc\"][0]\n",
    "    assist = \"\"\n",
    "elif len(df_bian[df[\"变\"]==\"变\"])==1:\n",
    "    # main = \"本卦\"+str(6-int(df[df[\"变\"]==\"变\"][\"index\"]))+\"爻\"\n",
    "    say = \"有变爻，取本卦变爻爻辞\"\n",
    "    main = pd.read_sql(sql_y%(str(6-int(df[df[\"变\"]==\"变\"][\"index\"])),gua_str),con)[\"desc\"][0]\n",
    "    assist = \"\"\n",
    "elif len(df_bian[df[\"变\"]==\"变\"])==2:\n",
    "    say = \"有二变爻，取本卦变爻爻辞，以上爻为主，下爻为辅\"\n",
    "    # main = \"本卦\"+str(6-min(df[df[\"变\"]==\"变\"][\"index\"]))+\"爻\"\n",
    "    main = pd.read_sql(sql_y%(str(6-min(df[df[\"变\"]==\"变\"][\"index\"])),gua_str),con)[\"desc\"][0]\n",
    "    # assist = \"本卦\"+str(6-max(df[df[\"变\"]==\"变\"][\"index\"]))+\"爻\"\n",
    "    assist = pd.read_sql(sql_y%(str(6-max(df[df[\"变\"]==\"变\"][\"index\"])),gua_str),con)[\"desc\"][0]\n",
    "elif len(df[df[\"变\"]==\"变\"])==3:\n",
    "    say = \"有三变爻，取本卦卦辞为主，之卦卦辞为辅\"\n",
    "    main = pd.read_sql(sql_g%gua_str,con)[\"desc\"][0]\n",
    "    assist = pd.read_sql(sql_g%zhi_str,con)[\"desc\"][0]\n",
    "elif len(df[df[\"变\"]==\"变\"])==4:\n",
    "    say = \"有四变爻，取之卦变爻爻辞，以下爻为主，上爻为辅\"\n",
    "    # main = \"变卦\"+str(6-max(df[df[\"变\"]==\"不变\"][\"index\"]))+\"爻\"\n",
    "    main = pd.read_sql(sql_y%(str(6-max(df[df[\"变\"]==\"不变\"][\"index\"])),zhi_str),con)[\"desc\"][0]\n",
    "    # assist = \"变卦\"+str(6-min(df[df[\"变\"]==\"不变\"][\"index\"]))+\"爻\"\n",
    "    assist = pd.read_sql(sql_y%(str(6-min(df[df[\"变\"]==\"不变\"][\"index\"])),zhi_str),con)[\"desc\"][0]\n",
    "elif len(df_bian[df[\"变\"]==\"变\"])==5:\n",
    "    say = \"有五变爻，取之卦不变爻爻辞\"\n",
    "    # main = \"变卦\"+str(df[df[\"变\"]==\"不变\"][\"index\"])+\"爻\"\n",
    "    main = pd.read_sql(sql_y%(str(6-df[df[\"变\"]==\"不变\"][\"index\"]),zhi_str),con)[\"desc\"][0]\n",
    "    assist = \"\"\n",
    "elif len(df[df[\"变\"]==\"变\"])==6:\n",
    "    if zhi_str in (\"111111\",\"000000\"):\n",
    "        say =\"乾坤两卦，取本卦用爻爻辞\"\n",
    "        main = \"本卦\"+str(7)+\"爻\"\n",
    "        main = pd.read_sql(sql_y%(str(7),gua_str),con)[\"desc\"][0]\n",
    "        assist = \"\"\n",
    "    else:\n",
    "        say = \"取之卦卦辞\"\n",
    "        main = pd.read_sql(sql_g%zhi_str,con)[\"desc\"][0]\n",
    "        assist = \"\""
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 27,
   "metadata": {},
   "outputs": [
    {
     "output_type": "execute_result",
     "data": {
      "text/plain": "{'in': '震卦',\n 'in_g': '震：亨。震来虩虩，笑言哑哑。震惊百里，不丧匕鬯。',\n 'change': '',\n 'out_g': '',\n 'say': '无变爻，取本卦卦辞',\n 'main': '震：亨。震来虩虩，笑言哑哑。震惊百里，不丧匕鬯。',\n 'assist': ''}"
     },
     "metadata": {},
     "execution_count": 27
    }
   ],
   "source": [
    "#汇总成文\n",
    "if df_in[\"hexagram\"][0]==df_out[\"hexagram\"][0]:\n",
    "    change = \"\"\n",
    "    in_g = pd.read_sql(sql_g%gua_str,con)[\"desc\"][0]\n",
    "    out_g = \"\"\n",
    "else:\n",
    "    change = df_out[\"hexagram\"][0]\n",
    "    in_g = pd.read_sql(sql_g%gua_str,con)[\"desc\"][0]\n",
    "    out_g = pd.read_sql(sql_g%zhi_str,con)[\"desc\"][0]\n",
    "total  = {\n",
    "    \"in\" : df_in[\"hexagram\"][0],\n",
    "    \"in_g\" : in_g,  \n",
    "    \"change\" : change,\n",
    "    \"out_g\" : out_g,\n",
    "    \"say\" : say,\n",
    "    \"main\" : main,\n",
    "    \"assist\" : assist\n",
    "}\n",
    "total"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 28,
   "metadata": {},
   "outputs": [
    {
     "output_type": "execute_result",
     "data": {
      "text/plain": "     数    卦   变    之\n0  8.0  - -  不变  - -\n1  8.0  - -  不变  - -\n2  7.0  ---  不变  ---\n3  8.0  - -  不变  - -\n4  8.0  - -  不变  - -\n5  7.0  ---  不变  ---",
      "text/html": "<div>\n<style scoped>\n    .dataframe tbody tr th:only-of-type {\n        vertical-align: middle;\n    }\n\n    .dataframe tbody tr th {\n        vertical-align: top;\n    }\n\n    .dataframe thead th {\n        text-align: right;\n    }\n</style>\n<table border=\"1\" class=\"dataframe\">\n  <thead>\n    <tr style=\"text-align: right;\">\n      <th></th>\n      <th>数</th>\n      <th>卦</th>\n      <th>变</th>\n      <th>之</th>\n    </tr>\n  </thead>\n  <tbody>\n    <tr>\n      <th>0</th>\n      <td>8.0</td>\n      <td>- -</td>\n      <td>不变</td>\n      <td>- -</td>\n    </tr>\n    <tr>\n      <th>1</th>\n      <td>8.0</td>\n      <td>- -</td>\n      <td>不变</td>\n      <td>- -</td>\n    </tr>\n    <tr>\n      <th>2</th>\n      <td>7.0</td>\n      <td>---</td>\n      <td>不变</td>\n      <td>---</td>\n    </tr>\n    <tr>\n      <th>3</th>\n      <td>8.0</td>\n      <td>- -</td>\n      <td>不变</td>\n      <td>- -</td>\n    </tr>\n    <tr>\n      <th>4</th>\n      <td>8.0</td>\n      <td>- -</td>\n      <td>不变</td>\n      <td>- -</td>\n    </tr>\n    <tr>\n      <th>5</th>\n      <td>7.0</td>\n      <td>---</td>\n      <td>不变</td>\n      <td>---</td>\n    </tr>\n  </tbody>\n</table>\n</div>"
     },
     "metadata": {},
     "execution_count": 28
    }
   ],
   "source": [
    "#图示\n",
    "df[[\"数\",\"卦\",\"变\",\"之\"]]"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": []
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.8.3-final"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 2
}